package com.qx.grainmall.cart.controller;

import com.qx.common.utils.R;
import com.qx.grainmall.cart.service.CartService;
import com.qx.grainmall.cart.vo.CartItemVo;
import com.qx.grainmall.cart.vo.CartVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
public class CartController {

    @Autowired
    private CartService cartService;
    @RequestMapping("cartList")
    public String tocart(){
        return "cartList";
    }

    @RequestMapping("addToCart")
    public String success(@RequestParam("skuId")Long skuId,
                          @RequestParam("num")Integer num,
                          Model model,
                          RedirectAttributes attributes){

        CartItemVo cartItemVo = cartService.addToCart(skuId, num);
        model.addAttribute("skuInfo",cartItemVo);
        //重定向传参
        attributes.addAttribute("skuId",skuId);
        return "redirect:http://cart.gulimall.com/success";
    }
    //跳转页面
    @GetMapping("success")
    public String success(@RequestParam("skuId") Long skuId,
                          Model model){
//        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
//        System.out.println(userInfoTo);
        //查询当前用户+当前商品在购物车中的数据
        CartItemVo cartItemVo = cartService.getCart(skuId);
        model.addAttribute("skuInfo",cartItemVo);
        return "success";
    }

    //去购物车结算
    @GetMapping("cartList")
    public String cart(Model model){
        //获取当前用户购物车
        CartVo vo = cartService.getAllCartVo();
        model.addAttribute("cartVo",vo);
        return "cartList";
    }

    //更改是否选中
    @GetMapping("checkItem")
    public String checkItem(@RequestParam("skuId") Long skuId,
                            @RequestParam("check") Boolean check,
                            RedirectAttributes attributes){
        cartService.changeCheck(skuId,check);
        return "redirect:http://cart.gulimall.com/cartList";
    }
    //更改数量
    @GetMapping("updCount")
    public String updCount(@RequestParam("skuId") Long skuId,
                           @RequestParam("num") Integer num,
                           RedirectAttributes attributes){
        cartService.updCount(skuId,num);
        return "redirect:http://cart.gulimall.com/cartList";
    }
    //更改数量
    @RequestMapping("del")
    public String del(@RequestParam("skuId") Long skuId,
                      RedirectAttributes attributes){
        cartService.del(skuId);
        return "redirect:http://cart.gulimall.com/cartList";
    }
}
